// pages/home/home.js
var aliyun_api = require('../../utils/aliyun-api-gateway.js');
var util = require('../../utils/util.js');
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //判断小程序的API，回调，参数，组件等是否在当前版本可用。
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    vercode: '123',
    index: null,
    hasDevice:true,
    lockList:[],
    bHidden: false,
    height:300,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this

    that.setData({
      index:1
    })

    that.InitStruct()
  //  that.authorize()
    that.setData({
      height: (app.globalData.SystemInfo.windowHeight * (750 / app.globalData.SystemInfo.windowWidth))-400-350-150
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

/**
 * @description: 授权页
 * @param {type} 
 * @return: 
 */  
  authorize:function () {
    var that = this;
    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      }
    })
    // 查看是否授权
    wx.getSetting({
      success: function (res) {
      //  if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: function (res) {
              //用户已经授权过
              that.login()
            },
            fail: function (res) {
              that.setData({
                index: 0
              })
            }
          });
      //  }
      }
    })
  },

  bindGetUserInfo: function (e) {
    var that = this;
    util.NetStatusOk().then(function () {
      if (e.detail.userInfo) {
        //用户按了允许授权按钮
        app.globalData.userInfo = e.detail.userInfo;
        //授权成功后，跳转进入小程序首页
        wx.setNavigationBarTitle({
          title: '登录'
        })
        that.setData({
          index: 1
        })
      } else {
        //用户按了拒绝按钮
        wx.showModal({
          title: '警告',
          content: '您点击了拒绝授权，将无法进入小程序，请授权之后再进入!!!',
          showCancel: false,
          confirmText: '返回授权',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击了“返回授权”')
            }
          }
        })
      }
    })
  },

  /**
   * @description: login页
   * @param {type} 
   * @return: 
   */  
  /**获取验证码 */
  formsubmit1: function (e) {
    console.log(e.detail.value.phone)
    console.log("获取验证码")
    var that = this
    if (e.detail.value.phone === '') {
      wx.showToast({
        title: '请填写手机号',
        icon: 'none',
        duration: 2000
      })
      return
    }
    if (!util.checkPhone(e.detail.value.phone)) {
      wx.showToast({
        title: '手机号格式有误',
        icon: 'none',
        duration: 2000
      })
      return
    }
    util.NetStatusOk().then(function () {
      const params = {
        url: 'https://api.link.aliyun.com/kvstore/get',
        apiVer: '1.1.0',
        param: {
          "key": e.detail.value.phone
        }
      }
      aliyun_api.request(params).then(function (res) {
        //  console.log(data)
        if (res.data) {
          util.SendSms(e.detail.value.phone).then(code => {
            that.getCode()
            that.setData({
              vercode: code
            })
            var loginInfo = {
              phone: e.detail.value.phone,
              vercode: code,
              time: Date.now()
            }
            wx.setStorageSync('loginInfo', loginInfo)
          })
          .catch(res => {
            var msg = ''
            if (res.code === 0) {
              msg = '\r\n(' + res.res.result.data.Message + ')'
            } else if (res.code === 1) {
              msg = '\r\n(' + '服务器异常' + ')'
              console.log(res)
            }
            wx.showToast({
              title: '短信验证码发送失败' + msg,
              icon: 'none',
              duration: 2000
            })
          })
        } else {
          wx.showToast({
            title: '账号不存在，请前往app注册',
            icon: 'none',
            duration: 2000
          })
        }
      })
      .catch(res => {
        wx.showToast({
          title: '云端请求失败',
          icon: 'none',
          duration: 2000
        })
      })
    })
  },
  cancel: function () {
    wx.switchTab({
      url: '/pages/home/home',
    })
  },
  /**登录 */
  formsubmit: function (e) {
    console.log(e.detail.value)
    console.log("下一步")

    if (e.detail.value.phone === '12345678') {
      wx.setStorageSync('accountInfo', '12345678')
      wx.switchTab({
        url: '/pages/home/home',
      })
      return
    }

    if (e.detail.value.phone === '') {
      wx.showToast({
        title: '请填写手机号',
        icon: 'none',
        duration: 2000
      })
      return
    }
    if (e.detail.value.vercode === '') {
      wx.showToast({
        title: '请填写验证码',
        icon: 'none',
        duration: 2000
      })
      return
    }
    util.NetStatusOk().then(function () {
      var loginInfo = wx.getStorageSync('loginInfo')
      console.log('loginInfo:', loginInfo)
      if (loginInfo !== '') {
        if ((e.detail.value.phone === loginInfo.phone) &&
          (e.detail.value.vercode === loginInfo.vercode) &&
          (Date.now() <= (loginInfo.time + 5 * 60 * 1000))) {
          try { //存入缓存
            wx.removeStorageSync('loginInfo')
            wx.setStorageSync('accountInfo', e.detail.value.phone)
            wx.switchTab({
              url: '/pages/home/home',
            })
          } catch (e) {
            console.log('fail')
          }
        } else {
          if ((e.detail.value.phone === loginInfo.phone) &&
            (e.detail.value.vercode === loginInfo.vercode) &&
            (Date.now() > (loginInfo.time + 5 * 60 * 1000))) {
            wx.showToast({
              title: '验证码过期，请重新获取验证码',
              icon: 'none',
              duration: 2000
            })
          } else {
            wx.showToast({
              title: '验证码错误',
              icon: 'none',
              duration: 2000
            })
          }
        }
      } else {
        wx.showToast({
          title: '验证码错误',
          icon: 'none',
          duration: 2000
        })
        // wx.removeStorageSync('loginInfo')
        // wx.setStorageSync('accountInfo', e.detail.value.phone)
        // wx.switchTab({
        //   url: '/pages/home/home',
        // })
      }
    })
  },

  login: function () {
    var that = this
    try {
      const value = wx.getStorageSync('accountInfo')
      if (value) {
        const params = {
          url: 'https://api.link.aliyun.com/kvstore/get',
          apiVer: '1.1.0',
          param: {
            "key": value
          }
        }
        aliyun_api.request(params).then(function (res) {
          //  console.log(data)
          if (res.data) {
            wx.switchTab({
              url: '/pages/home/home',
            })
            console.log("已登录");
            console.log(value);
          } else {
            console.log("账号不存在，重新登录");
            wx.setNavigationBarTitle({
              title: '登录'
            })
            that.setData({
              index: 1
            })
          }
        })
      } else {
        console.log("未登录");
        wx.setNavigationBarTitle({
          title: '登录'
        })
        that.setData({
          index: 1
        })
      }
    } catch (e) {
      // Do something when catch error
      console.log('none')
    }
  },

  InitStruct: function () {
    app.globalData.BLE.bleData = new util.ByteArray()
    var devInfo = new util.DevInfo()
    var lockOpInfo = new util.LockOpInfo()

    try {
      var value = wx.getStorageSync('deviceInfo')
      if (value) {
        // Do something with return value
        ///  console.log(111)
      } else {
        wx.setStorageSync('deviceInfo', devInfo)
        ///  console.log(222)
      }
    } catch (e) {
      // Do something when catch error
      //  console.log(333)
    }
    try {
      var value = wx.getStorageSync('lockOpInfo')
      if (value) {

      } else {
        wx.setStorageSync('lockOpInfo', lockOpInfo)
      }
    } catch (e) {

    }
  },

  getCode: function () {
    var that = this;
    var time = 60;
    that.setData({
      second: 60,
      bHidden: true
    })
    var interval = setInterval(function () {
      time--;
      if (time > 0) {
        that.setData({
          second: time
        });
      } else {
        clearInterval(interval);
        that.setData({
          bHidden: false
        });
      }
    }, 1000)
  },
})